package org.lpw.wormhole.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.codec.binary.Hex;

/**
 * @author lpw
 */
public class ConverterImpl
    implements Converter
{
    private static final String BLANK = "";// 空字符串。

    private final Kit kit;

    public ConverterImpl(Kit kit)
    {
        super();

        this.kit = kit;
    }

    @Override
    public String[] toArray(String string, String separator)
    {
        if(string==null)
            return new String[0];

        if(BLANK.equals(string)||separator==null||BLANK.equals(separator)||string.indexOf(separator)==-1)
            return new String[]{string};

        return string.split(separator);
    }

    @Override
    public String serializeToHexString(Object object)
    {
        if(object==null)
            return null;

        try
        {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            ObjectOutputStream objectOutput = new ObjectOutputStream(output);
            objectOutput.writeObject(object);
            objectOutput.close();
            objectOutput = null;
            output.close();

            return Hex.encodeHexString(output.toByteArray());
        }
        catch(Exception e)
        {
            kit.getLogger().warn(e, "序列化对象为十六进制字符串时发生异常！");

            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserializeFromHexString(String string)
    {
        if(string==null)
            return null;

        try
        {
            ByteArrayInputStream input = new ByteArrayInputStream(Hex.decodeHex(string.toCharArray()));
            ObjectInputStream objectInput = new ObjectInputStream(input);
            Object object = objectInput.readObject();
            objectInput.close();
            objectInput = null;
            input.close();
            input = null;

            return (T)object;
        }
        catch(Exception e)
        {
            kit.getLogger().warn(e, "反序列化十六进制字符串为对象时发生异常！");

            return null;
        }
    }
}
